# coding: utf-8
import tornado.ioloop
import tornado.web
import tornado
import json
import math
import datetime
from bson import ObjectId
from handlers.base import BaseHandler


class BloodPressureHandler(BaseHandler):
    @tornado.gen.coroutine
    def get(self):
        try:
            rid = self.get_query_argument('rid')
        except Exception as err:
            self.response_msg(400, '参数错误')
            return
        # 判断page是否存在
        skip = 0
        limit = 7
        results = []
        try:
            if 'page' in self.request.arguments:
                page = self.get_argument('page')
                if not page:
                    page = 1
                # 返回对应page的list
                limit = 20
                skip = (int(page) - 1) * limit
            # 下面就是查询语句
            where = {}
            where['role'] = rid
            where['measureType'] = 'pressure'
            # 限制返回字段
            fieldList = {}
            fieldList['_id'] = 1
            fieldList['pressureHigh'] = 1
            fieldList['pressureLow'] = 1
            fieldList['heartRate'] = 1
            fieldList['created_at'] = 1
            fieldList['advice'] = 1
            # 组装语句
            listRes = self.db.HMMeasure.find(where, fieldList).sort('created_at', -1).skip(skip).limit(limit)
            while (yield listRes.fetch_next):
                tempObj = listRes.next_object()
                tempObj['objectId'] = str(tempObj['_id'])
                tempObj['created_at'] = tempObj['created_at'].strftime("%Y-%m-%d %H:%M")
                del tempObj['_id']
                # 获取建议
                if 'page' in self.request.arguments:
                    advice = yield self.db.HMMeasureAdvice.find_one({'_id': ObjectId(tempObj['advice'])})
                    tempObj['adviceStr'] = advice['diet']
                results.append(tempObj)
            self.response_msg(200, "获取成功", results)
        except Exception as e:
            print(e)
            self.response_msg(500, str(e))

    @tornado.gen.coroutine
    def post(self):
        try:
            rid = self.get_argument('rid')
            heartRate = self.get_argument('heartRate')
            heartRate = int(heartRate)
            pressureLow = self.get_argument('pressureLow')
            pressureLow = int(pressureLow)
            pressureHigh = self.get_argument('pressureHigh')
            pressureHigh = int(pressureHigh)
            create_at = self.get_argument('created_at')
            create_at = datetime.datetime.strptime(create_at, '%Y-%m-%dT%H:%M:%S')
        except Exception as e:
            self.response_msg(400, '参数错误')
            return
        try:
            # 确定低压范围
            pressure_list = ['血压低', '血压正常', '血压偏高', '血压偏高', '血压偏高', '重度高压']
            low_tag = 1
            high_tag = 1
            # 判断低压的区间
            if pressureLow < 60:
                low_tag = 0
            elif pressureLow >= 60 and pressureLow < 85:
                low_tag = 1
            elif pressureLow >= 85 and pressureLow < 90:
                low_tag = 2
            elif pressureLow >= 90 and pressureLow < 100:
                low_tag = 3
            elif pressureLow >= 100 and pressureLow < 110:
                low_tag = 4
            elif pressureLow >= 110:
                low_tag = 5
            # 判断高压的区间
            if pressureHigh < 90:
                high_tag = 0
            elif pressureHigh >= 90 and pressureHigh < 130:
                high_tag = 1
            elif pressureHigh >= 130 and pressureHigh < 140:
                high_tag = 2
            elif pressureHigh >= 140 and pressureHigh < 160:
                high_tag = 3
            elif pressureHigh >= 160 and pressureHigh < 180:
                high_tag = 4
            elif pressureHigh >= 180:
                high_tag = 5
            # 根据高压和低压区间确定 血压范围
            if high_tag == 1 or low_tag == 1:
                tag = low_tag if high_tag == 1 else high_tag
            else:
                tag = low_tag
            tag = pressure_list[tag]
            if pressureHigh >= 140 and (pressureLow < 85 and pressureLow >= 60):
                tag = '单纯收缩期高压'
            # 根据判断结果获取建议对象
            advice = yield self.db.HMMeasureAdvice.find_one({'tag': tag})
            pressure = yield self.db.HMMeasure.save({'role': rid, 'heartRate': heartRate, 'measureType': 'pressure',
                                                     'pressureLow': pressureLow, 'pressureHigh': pressureHigh,
                                                     'created_at': create_at, 'advice': str(advice['_id'])
                                                     })
            self.response_msg(200, '保存成功', {'objectId': str(pressure)})
        except Exception as e:
            self.response_msg(500, '保存失败')
